package net.brucecooper.mindmapgadget.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public abstract class UploadDownloadServlet extends HttpServlet {

    private static final String UPLOAD = "upload.";

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uuid = null;
        String fileContents = null;
        
        log("Received post to " + request.getRequestURI());

        if (request.getContentType().startsWith("multipart/form-data")) {

            ServletFileUpload upload = new ServletFileUpload();

            try {
                FileItemIterator iterator = upload.getItemIterator(request);

                while (iterator.hasNext()) {
                    FileItemStream item = iterator.next();
                    BufferedReader r = new BufferedReader(new InputStreamReader(item.openStream()));

                    StringBuilder contents = new StringBuilder();
                    String line = null;
                    boolean first = true;
                    while ((line = r.readLine()) != null) {
                        if (first) {
                            first = false;
                        } else {
                            contents.append('\n');
                        }
                        contents.append(line);
                    }

                    if (item.isFormField()) {
                        uuid = contents.toString();
                    } else {
                        fileContents = contents.toString();
                    }

                    // Don't print anything out, otherwise the form will change
                    // page on the GWT component;
                }
            } catch (FileUploadException e) {
                throw new IOException("Error processing uploaded file: " + e);
            }
        } else {
            uuid = request.getParameter("id");
            fileContents = request.getParameter("contents");
        }
        log("ID is " + uuid + ", contents is " + fileContents);
        getServletContext().setAttribute(UPLOAD + uuid, fileContents);
    }


    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        String contents = (String) getServletContext().getAttribute(UPLOAD + id);
        getServletContext().removeAttribute(UPLOAD+id);
        log("Received get to " + request.getRequestURI() + " with ID " + id + ".  Contents is " + contents);;
        
        if (contents == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else {
            String result = convertToResult(contents);
            response.setContentType(getResultContentType());
            response.setCharacterEncoding("UTF-8");

            System.err.println("result is" + result.toString() + " for id " + id);
            response.getWriter().println(result.toString());
        }
    }

    protected abstract String getResultContentType();

    protected abstract String convertToResult(String contents) throws IOException;

}
